<?php

error_reporting( E_ALL | E_STRICT );
set_time_limit( 0 );
ignore_user_abort();

function _cf_finish_deploy_shutdown_1()
{
    if ( !empty( $GLOBALS[ 'CF_LOCK_FILE_POINTER' ] ) ) {
        flock( $GLOBALS[ 'CF_LOCK_FILE_POINTER' ], LOCK_UN );
        fclose( $GLOBALS[ 'CF_LOCK_FILE_POINTER' ] );
    }
}

;
register_shutdown_function( '_cf_finish_deploy_shutdown_1' );

function _cf_finish_deploy_shutdown_2()
{

    if ( $GLOBALS[ 'CF_DEPLOY_COMPLETED' ] ) {


        if ( CF_BUILD > 0 ) { //ya hay un despliegue anterior
            $ext = extension_loaded( 'zlib' ) ? 'tar.gz' : ( extension_loaded( 'bz2' ) ? 'bz2' : 'tar' );

            $package = new TarArchive( CF_BUILD_PATH . 'config' . DIRECTORY_SEPARATOR . CF_LAST_BUILD . '.' . $ext );
            $package->createModify( array( CF_BUILD_PATH . 'config' . DIRECTORY_SEPARATOR . CF_LAST_BUILD ),
                    '',
                    CF_BUILD_PATH . 'config' . DIRECTORY_SEPARATOR . CF_LAST_BUILD );
            unset( $package );
            rmtree( CF_BUILD_PATH . 'config' . DIRECTORY_SEPARATOR . CF_LAST_BUILD );

            $package = new TarArchive( CF_BUILD_PATH . 'config' . DIRECTORY_SEPARATOR . CF_LAST_BUILD . '.' . $ext );
            $package->createModify( array( CF_BUILD_PATH . 'config' . DIRECTORY_SEPARATOR . CF_LAST_BUILD ),
                    '',
                    CF_BUILD_PATH . 'config' . DIRECTORY_SEPARATOR . CF_LAST_BUILD );
            unset( $package );
            rmtree( CF_BUILD_PATH . 'config' . DIRECTORY_SEPARATOR . CF_LAST_BUILD );

            $package = new TarArchive( CF_BUILD_PATH . 'config' . DIRECTORY_SEPARATOR . CF_LAST_BUILD . '.' . $ext );
            $package->createModify( array( CF_BUILD_PATH . 'config' . DIRECTORY_SEPARATOR . CF_LAST_BUILD ),
                    '',
                    CF_BUILD_PATH . 'config' . DIRECTORY_SEPARATOR . CF_LAST_BUILD );
            unset( $package );
            rmtree( CF_BUILD_PATH . 'config' . DIRECTORY_SEPARATOR . CF_LAST_BUILD );
        }



        //SECCION CRITICA tratamos que sea lo más pequeña posible
        $fp_build = fopen( CF_BUILD_PATH . 'build.inc', 'w' );
        flock( $fp_build, LOCK_EX );

        fwrite( $fp_build, '<?php define(\'\',' . CO_BUILD . '\'); ?>' );

        flock( $fp_build, LOCK_UN );
        fclose( $fp_build );

        file_put_contents( CF_LOG_PATH . 'deploy.time', time() );
    } else {
        //Esto deberia loguear un error porque es una situación de excepcion
        //no lo vamos a eliminar pq queremos ver los logs
        // rmtree(CF_BUILD_PATH . 'config' . DIRECTORY_SEPARATOR . 'deploy');
        // rmtree(CF_BUILD_PATH . 'src' . DIRECTORY_SEPARATOR . 'deploy');
        // rmtree(CF_BUILD_PATH . 'logs' . DIRECTORY_SEPARATOR . 'deploy');
    }
}

;
register_shutdown_function( '_cf_finish_deploy_shutdown_2' );

function _cf_add_to_classpath( $path, $baselength )
{

    if ( $baselength == null ) $baselength = strlen( $path );

    $base = substr( $path, $baselength );

    $files = array_diff( scandir( $path ), array( '.', '..' ) );

    foreach ( $files as $f ) {

        if ( is_dir( $path . $f ) ) {

            if ( !file_exists( $base . $f ) ) mkdir( $base . $f );

            _cf_add_to_classpath( $path . $f . DIRECTORY_SEPARATOR, $baselength );
        }
        else copy( $path . $f, $base . $f );
    }
}

//PUEDO UTILIZAR EL DIRECTORIO 0 O EL DIRECTORIO TEMPORAL
//LO BUENO DEL DIRECTORIO TEMPORAL ES QUE PUEDE ESTAR EN MEMORIA
//define('CF_BASE_PATH', sys_get_temp_dir() . realpath(dirname(__FILE__)) . DIRECTORY_SEPARATOR);
//define('CF_BUILD_PATH', CF_BASE_PATH );

define( 'CF_BASE_PATH', realpath( dirname( __FILE__ ) ) . DIRECTORY_SEPARATOR );
define( 'CF_HTTP_BASE_PATH',
        substr( CF_BASE_PATH, strlen( $_SERVER[ 'DOCUMENT_ROOT' ] ) ) );
define( 'CF_HTTP_SCRIPT',
        substr( $_SERVER[ 'SCRIPT_FILENAME' ],
                strlen( $_SERVER[ 'DOCUMENT_ROOT' ] ) ) );
define( 'CF_HTTP_PATH',
        ( dirname( CF_HTTP_SCRIPT ) == '/' ) ? '/' : dirname( CF_HTTP_SCRIPT ) . '/'  );
define( 'CF_BUILD_PATH', CF_BASE_PATH . '0' . DIRECTORY_SEPARATOR );

if ( !file_exists( CF_BUILD_PATH ) )
        exit( 'You must create a writeable directory called \'0\'' );


define( 'CF_CACHE_PATH', CF_BUILD_PATH . 'cache' . DIRECTORY_SEPARATOR );

if ( !file_exists( CF_BUILD_PATH . 'cache' ) ) mkdir( CF_BUILD_PATH . 'cache' );


define( 'CF_TEMP_PATH', CF_BUILD_PATH . 'temp' . DIRECTORY_SEPARATOR );

if ( !file_exists( CF_BUILD_PATH . 'temp' ) ) mkdir( CF_BUILD_PATH . 'temp' );



//Tengo que tener un archivo de bloque para no poder ejecutar dos veces al mismo tiempo el deploy

if ( file_exists( CF_BUILD_PATH . 'build.inc' ) ) {

    $GLOBALS[ 'CF_LOCK_FILE_POINTER' ] = fopen( CF_BUILD_PATH . 'build.inc', 'r' );
    flock( $GLOBALS[ 'CF_LOCK_FILE_POINTER' ], LOCK_SH );
    $ct_build_script = file_get_contents( CF_BUILD_PATH . 'build.inc', 'r' );
    flock( $GLOBALS[ 'CF_LOCK_FILE_POINTER' ], LOCK_UN );
    fclose( $GLOBALS[ 'CF_LOCK_FILE_POINTER' ] );

    $matches = array( );
    if ( preg_match( '/\s*<?\s*define(\s*\'CF_BUILD\'\s*,\s*(\d+)\s*)/',
                    $ct_build_script ) )
            define( 'CF_BUILD', 1 + $matches[ 1 ] );

    else {
        //el ultimo build metió un dato corrupto en el build.inc con lo que debo buscar la ultima carpeta
        //dentro de CF_BUILD_PATH . 'logs' que es la primera que se crea

        $dirs = array_diff( scandir( CF_BUILD_PATH . 'logs' . DIRECTORY_SEPARATOR ),
                array( '.', '..' ) );
        define( 'CF_BUILD', ( int ) max( $dirs ) );
    }
} else {
    //Puedo haber un problema al crear el archivo
    $dirs = array_diff( scandir( CF_BUILD_PATH . 'logs' . DIRECTORY_SEPARATOR ),
            array( '.', '..' ) );
    define( 'CF_BUILD', ( int ) max( $dirs ) );
}

define( 'CF_LAST_BUILD', CF_BUILD - 1 );

require_once 'copperfunctions.inc.php';


define( 'CF_LOG_PATH',
        CF_BUILD_PATH . 'logs' . DIRECTORY_SEPARATOR . CF_BUILD . DIRECTORY_SEPARATOR );

//si existen los archivos de un build anterior los tengo que eliminar
if ( file_exists( CF_LOG_PATH ) ) rmtree( CF_LOG_PATH );


//Queremos que sólo un feploy se ejecute a la vez, de esta forma lo controlamos
if ( @mkdir( CF_LOG_PATH ) ) {

    define( 'CF_LAST_CONFIG_PATH',
            CF_BUILD_PATH . 'config' . DIRECTORY_SEPARATOR . CF_LAST_BUILD . DIRECTORY_SEPARATOR );

    define( 'CF_CONFIG_PATH',
            CF_BUILD_PATH . 'config' . DIRECTORY_SEPARATOR . CF_BUILD . DIRECTORY_SEPARATOR );

    if ( file_exists( CF_CONFIG_PATH ) ) rmtree( CF_CONFIG_PATH );

    mkdir( CF_CONFIG_PATH );

    define( 'CF_CLASS_PATH',
            CF_BUILD_PATH . 'src' . DIRECTORY_SEPARATOR . CF_BUILD . DIRECTORY_SEPARATOR );

    if ( file_exists( CF_CLASS_PATH ) ) rmtree( CF_CLASS_PATH );

    mkdir( CF_CLASS_PATH );


    /*
      if ( !file_exists(CF_BUILD_PATH.'.htaccess') ) {

      $htaccess = '
      <IfModule mod_rewrite.c>
      SetEnv HTTP_MOD_REWRITE ON

      RewriteEngine on
      RewriteBase '.CF_HTTP_BASE_PATH.'0/
      #    RewriteCond %{REQUEST_FILENAME} !-f
      #    RewriteCond %{REQUEST_FILENAME} !-d
      RewriteRule (.*)//(.*) '.CF_HTTP_BASE_PATH.'$1/index.php/$2

      RewriteCond %{REQUEST_FILENAME} !-f
      RewriteRule (.*) '.CF_HTTP_BASE_PATH.'index.php/$1
      </IfModule>
      <IfModule !mod_rewrite.c>
      Options -Indexes\nDeny from all
      </IfModule>';

      file_put_contents(CF_BUILD_PATH.'.htaccess', $htaccess);
      }
     */

    if ( file_exists( CF_BASE_PATH . 'lib' ) && is_dir( F_BASE_PATH . 'lib' ) ) {

        $libs = array_diff( scandir( CF_BASE_PATH . 'lib' ), array( '.', '..' ) );

        foreach ( $libs as $l ) {
            //los archivos pueden ser tar, tar.gz, tgz, bz o bz2 siempre que los modulos de compresion estén disponibles

            if ( substr( $l, -4 ) == '.tar' || substr( $l, -7 ) == '.tar.gz' || substr( $l,
                            -4 ) == '.tgz' || substr( $l, -4 ) == '.bz2' || substr( $l,
                            -3 ) == '.bz' ) {

                $package = new TarArchive( CF_BASE_PATH . 'lib' . DIRECTORY_SEPARATOR . $l );
                $package->extract( CF_CLASS_PATH );
                unset( $package );

                if ( file_exists( CF_CLASS_PATH . 'deploy.php' ) ) {
                    $fp0 = fopen( CF_CLASS_PATH . 'deployall.php', 'a' );
                    $fp1 = fopen( CF_CLASS_PATH . 'deploy.php', 'r' );

                    while ( ( $data = fread( $fp1, 4096 ) ) !== false )
                        fwrite( $fp0, $data );

                    fclose( $fp0 );
                    fclose( $fp1 );

                    unlink( CF_CLASS_PATH . 'deploy.php' );
                }

                //if( file_exists( CF_CLASS_PATH . '.phar' . DIRECTORY_SEPARATOR . 'stub.php' ) ){
                //    include CF_CLASS_PATH . '.phar' . DIRECTORY_SEPARATOR . 'stub.php';
                //    rmtree(CF_CLASS_PATH . '.phar');
                //}
            }
        }
    }

    if ( file_exists( CF_BASE_PATH . 'src' ) && is_dir( CF_BASE_PATH . 'src' ) ) {

        if ( file_exists( CF_BASE_PATH . 'src' . DIRECTORY_SEPARATOR . 'deploy.php' ) ) {

            $fp0 = fopen( CF_CLASS_PATH . 'deployall.php', 'a' );
            $fp1 = fopen( CF_BASE_PATH . 'src' . DIRECTORY_SEPARATOR . 'deploy.php',
                    'r' );

            while ( ( $data = fread( $fp1, 4096 ) ) !== false )
                fwrite( $fp0, $data );

            fclose( $fp0 );
            fclose( $fp1 );

            unlink( CF_BASE_PATH . 'src' . DIRECTORY_SEPARATOR . 'deploy.php' );
        }

        _cf_add_to_classpath( CF_BASE_PATH . 'src' . DIRECTORY_SEPARATOR );
    }


    if ( file_exists( CF_CLASS_PATH . 'deployall.php' ) )
            include CF_CLASS_PATH . 'deployall.php';

    $GLOBALS[ 'CF_DEPLOY_COMPLETED' ] = 1;
}
else {
    /*
      $GLOBALS['CF_DEPLOY_COMPLETED'] = 0;

      $time = filemtime(CF_BUILD_PATH . 'config' . DIRECTORY_SEPARATOR . 'deploy');

      if( ($_SERVER['REQUEST_TIME'] - $time) > 10*60 ){ //si el directorio existe/no fue modificado desde hace más de 10 minutos entonces interpretamos que hubo problemas en el deploy anterior

      //ESTO DEBERÍA MOSTRAR UN ERROR!!! YA QUE ES UNA CIRCUNSTANCIA EXCEPCIONAL
      rmtree(CF_LOG_PATH);
      rmtree(CF_CONFIG_PATH);
      rmtree(CF_CLASS_PATH);
      }
     * 
     */
}
?>
